package cn.zz.veggie.application.task;

import org.slf4j.MDC;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import cn.zz.comm.core.constans.MdcConstants;
import cn.zz.comm.util.TranceUtil;
import cn.zz.veggie.application.service.PurchaseAppService;
import cn.zz.veggie.application.service.SettleAppService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

/**
 * @author zhongq
 * @since 2024/6/3
 */
@Slf4j
@Component
@EnableScheduling
@RequiredArgsConstructor
public class TimerTask {

	private final SettleAppService settleAppService;
	private final PurchaseAppService purchaseAppService;

	/**
	 * 每月一号 0点10分执行
	 */
	@Scheduled(cron = "0 10 0 1 * ?")
//	@Scheduled(initialDelay = 10_000)
	public void settleStatistics() {
		logPreTask();
		settleAppService.timerSettleStatistics();
	}

	/**
	 * 每天 21点、12 点执行  + 4 =>
	 */
	@Scheduled(cron = "0 10 12,21 * * ?")
	public void purchaseStatistics() {
		logPreTask();
		purchaseAppService.timerPurchaseStatistics();
	}

	public void logPreTask() {
		// 获取当前线程的堆栈元素
		StackTraceElement[] stackTraceElements = Thread.currentThread().getStackTrace();
		// 堆栈的第一个元素是getStackTrace()本身，所以返回第二个元素
		String methodName = stackTraceElements.length > 2 ? stackTraceElements[2].getMethodName() : "";
		MDC.put(MdcConstants.TranceId, TranceUtil.tranceId());
		log.info("start timer {} ", methodName);
	}
}